<!-- BookScanBorrow.vue -->
<template>
  <div id="BookScanBorrow">
    <div id="interactive" class="viewport"></div>
    <button @click="startScanning1">启动扫码</button>
    <button @click="stopScanning1">停止扫码</button>
    <p v-if="scanResult1">扫描结果: {{ scanResult1 }}</p>
    <p v-if="borrowMessage1">借阅状态: {{ borrowMessage1 }}</p>
  </div>
</template>

<script>
import Quagga from "quagga";
import { BookScanBorrowingAPI } from "@/request/api"; // 封装的借书接口
import { mapState } from "vuex";
import gettime from "../utlis/gettime";

export default {
  computed: {
    ...mapState(["username"]),
  },
  data() {
    return {
      scanResult1: null, // 用于存储当前借书的扫码结果
      borrowMessage1: null,
      isScanning: false,
      isRequesting: false, // 防止重复请求的标志
      detectedListener: null, // 用于存储onDetected事件的侦听器引用
    };
  },
  methods: {
    startScanning1() {
      if (this.isScanning) {
        return;
      }

      // 清空之前的扫描结果
      this.scanResult1 = null;
      this.borrowMessage1 = null;

      const options = {
        inputStream: {
        type: "LiveStream",
        target: "#interactive",
        constraints: {
          width: { min: 350, ideal: 64 }, // 设置理想的宽度为64像素
          height: { min: 400 }, // 高度可以保持最小值，因为宽度是固定的
          facingMode: "environment",
        },
      },
        locator: { patchSize: "medium", halfSample: true },
        numOfWorkers: 4,
        frequency: 10,
        decoder: {
          readers: [
            "code_128_reader",
            "ean_reader",
            "ean_8_reader",
            "code_39_vin_reader",
            "codabar_reader",
          ],
        },
        locate: true,
      };

      Quagga.init(options, (err) => {
        if (err) {
          console.error("Quagga initialization failed:", err);
          return;
        }

        // 移除旧的侦听器（如果存在）
        if (this.detectedListener) {
          Quagga.offDetected(this.detectedListener);
        }

        // 创建并绑定新侦听器
        this.detectedListener = this.handleDetected1.bind(this);
        Quagga.onDetected(this.detectedListener);

        Quagga.start();
        this.isScanning = true;
      });
    },
    stopScanning1() {
      if (this.isScanning) {
        Quagga.stop();
        this.isScanning = false;
      }
    },
    handleDetected1(result) {
      const code = result?.codeResult?.code;
      if (code && !this.isRequesting) {
        this.scanResult1 = code; // 临时存储扫描结果
        this.stopScanning1(); // 停止扫描
        this.borrowBook1(code); // 处理借书请求
      }
    },
    async borrowBook1(code) {
      if (this.isRequesting) {
        console.log("请求正在处理中，请稍后...");
        return;
      }
      try {
        this.isRequesting = true;
        const params = {
          codeConst1: code,
          username1: this.username,
          borrowtime1: gettime(),
        };

        const response = await BookScanBorrowingAPI(params, {
          headers: { "Content-Type": "application/json" },
        });

        if (response.status === 1) {
          this.borrowMessage1 = "借书失败: 书籍或用户信息有误！";
          alert(this.borrowMessage1);
        } else {
          const bookname = response.data?.bookname || "未知书籍";
          const borrowTime = gettime();
          this.borrowMessage1 = `书籍 "${bookname}" 借阅成功！`;
          alert(`借阅成功！\n书名: ${bookname}\n借阅时间: ${borrowTime}`);

          // 跳转到用户借阅页面
          this.$router.push({ path: "/user/BookBorrowing" });
        }
      } catch (error) {
        console.error("Error borrowing book:", error);
        this.borrowMessage1 = "借书失败，请重试！";
        alert(this.borrowMessage1);
      } finally {
        this.isRequesting = false;
      }
    },
  },
  beforeDestroy() {
    // 确保在组件销毁前移除侦听器并停止扫描
    if (this.detectedListener) {
      Quagga.offDetected(this.detectedListener);
    }
    if (this.isScanning) {
      Quagga.stop();
    }
  },
};
</script>

<style scoped>
#interactive.viewport{
  width: 350px !important;
  height: 410px!important;
}
#interactive video {
  width: 350px !important;
}
#interactive canvas {
  width: 350px!important;
}
</style>